<template>
  <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" v-dialogDrag>
    <div class="app-container" style="display: flex;">
      <div>
        <el-card class="box-card">
          <el-form size="small" v-show="showSearch" label-width="120px">
            <el-form-item label="发货单编码" prop="nos">
              <el-input v-model="form.nos" placeholder="请输入发货通知编码"  disabled/>
            </el-form-item>
            <el-form-item label="客户" prop="kehuId">
              <el-select v-model="form.kehuId" placeholder="请选择客户" filterable @change="selectCustomer" clearable
                style="width: 300px">
                <el-option v-for="dict in dict.type.goods_customer" ref="myselectCustomer" :key="dict.value"
                  :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="联系人" prop="linkman">
               <el-input v-model="form.linkman" placeholder="请输入联系人"/>
            </el-form-item>
            <el-form-item label="联系电话" prop="linktel">
              <el-input v-model="form.linktel" placeholder="请输入联系电话" />
            </el-form-item>
            <el-form-item label="交货日期" prop="jiaohuoDate">
              <el-date-picker style="width: 100%;" clearable v-model="form.jiaohuoDate" type="date"
                value-format="yyyy-MM-dd" placeholder="请选择交货日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="发货日期" prop="fahuoDate">
              <el-date-picker style="width: 100%;" clearable v-model="form.fahuoDate" type="date"
                value-format="yyyy-MM-dd" placeholder="请选择交货日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="业务经理及电话" prop="jingli">
              <el-input v-model="form.jingli" placeholder="请输入业务经理及电话" />
            </el-form-item>
            <el-form-item label="收货地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入收货地址" />
            </el-form-item>
            <el-form-item label="发运方式" prop="shipType">
              <el-input v-model="form.shipType" type="textarea" placeholder="请输入发运方式" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea"  v-model="form.remark" placeholder="请输入备注"/>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
      <div style="width: calc(100% - 460px);margin-left: 10px;">
        <el-form :model="queryParams" ref="queryForm" :inline="true" size="small" v-show="showSearch"
          label-width="98px">
          <el-form-item label="产品名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入产品名称" style="width: 220px;" clearable
              @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item>
            <div style=" display: flex;margin-left: auto;">
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="primary" size="mini" @click="submitForm">添 加 发 货11</el-button>
            </div>
          </el-form-item>
        </el-form>
        <!-- <div style=" display: flex;align-items: center;margin-bottom: 10px;margin-top: 10px;">
          <el-button type="primary" size="mini" @click="submitForm">添 加 发 货</el-button>
        </div> -->
        <el-card class="box-card">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px" style="width: 100%;">
            <div v-if="dataList.length > 0">
            <div>已勾选通知发货数量合计: {{dataList.reduce((acc, row) => acc + row.shuliang, 0)}}</div>
        </div>
            <el-table border v-loading="loading" :data="columns" ref="table" @selection-change="handleSelectionChange" @sort-change="handleSortChange" :summary-method="totalOutYear" show-summary>
              <el-table-column fixed type="selection" width="55" align="center" />
              <el-table-column sortable label="通知单编号" align="center" prop="tongzhiNo" show-overflow-tooltip />
              <el-table-column sortable label="订单编号" align="center" prop="proNo" show-overflow-tooltip />
              <el-table-column sortable label="业务员" align="center" prop="saleman" />
              <el-table-column sortable label="产品编码" align="center" prop="nos" show-overflow-tooltip />
              <el-table-column sortable label="产品名称" align="center" prop="name" />
              <el-table-column sortable label="产品型号" align="center" prop="models" />
              <!-- <el-table-column label="产品明细" align="center" prop="mingxi"/> -->
              <el-table-column sortable label="产品单位" align="center" prop="danwei" />
              <el-table-column sortable label="通知发货数量" align="center" prop="shuliang" />
              <el-table-column sortable label="剩余发货数量" width="210">
                <template slot-scope="scope">
                  <el-input-number v-model="scope.row.shengyuCount" :min="0"></el-input-number>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark" />
              <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
            </el-table>
          </el-form>
        </el-card>
      </div>
    </div>
    <div style="margin-left: 10px;">
      <el-card class="box-card" style="margin-top: 10px;">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-table :data="columns2" ref="dragTable" row-key="id" v-loading="loading2" :summary-method="totalOutYear" show-summary>
            <el-table-column sortable label="业务员" align="center" prop="saleman" />
            <el-table-column sortable label="产品编码" align="center" prop="nos" show-overflow-tooltip/>
            <el-table-column sortable label="产品名称" align="center" prop="name" />
            <el-table-column sortable label="产品型号" align="center" prop="models"/>
            <el-table-column sortable label="产品单位" align="center" prop="danwei" />
            <el-table-column sortable label="产品单价" align="center" prop="danjian" />
            <el-table-column sortable label="发货数量" align="center" prop="shuliang" />
            <el-table-column label="备注" align="center" prop="remark" />
            <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="140">
              <template slot-scope="scope">
                <el-popconfirm :title="`确认删除 `+scope.row.name+` 数据项？`" @confirm="handleDelete(scope.row)"
                  style="margin-left: 10px;">
                  <el-button icon="el-icon-delete" size="mini" slot="reference" type="text"
                    v-hasPermi="['develop:ProjectBaseInfo:remove']">删除
                  </el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-card>
    </div>
    <div slot="footer" class="dialog-footer">
      <!--<el-button type="primary" @click="submitFormFahuodan">提交到财务审核</el-button>-->
      <el-button type="primary" @click="submitFormZancun">修改发货单</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {
    getAction,
    addAction,
    deleteAction,
    getById,
    updateAction,
    accAdd
  } from '@/api/manage'

  export default {
    name: "LvFahuoBohuiForm",
    dicts: ['goods_customer', 'yifahuo_status'],
    components: {},
    data() {
      return {
        title: "开始发货",
        open: false,
        // 遮罩层
        loading: true,
        loading2: true,
        // 选中数组
        ids: [],
        rows: [],
        form: {},
        rules: {},
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        total2: 0,
        // 销售信息管理表格数据
        dataList: [],
        //联系人
        columnsLinkman: [],
        columns: [],
        columns2: [],
        fahuoNo: "",
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          goodsCode: null,
          goodsName: null,
          goodModel: null,
          brand: null,
          projectName: null,
          projectNo: null,
          isfahuo: "0",
          params: {},
          customerCode: null,
          createName: null,
          salesmanName: null,
          orderDate: null,
          companyName: null,
          customName: null,
          deliveryPerson: null,
        },
        queryParams2: {
          pageNum: 1,
          pageSize: 20000,
          tongzhiId: null,
          fahuoId: null,
          name: null,
          brand: null,
          //status: "3",
          params: {},
        },
        queryParamsLinkman: {
          pageNum: 1,
          pageSize: 20000,
          customId: null,
          name: null,
          params: {},
        },
        url: {
          list: '/goodsSale/goodsSale/listSendNotZero',
          list2: '/lvYifahuomingxi/lvYifahuomingxi/listNoFahuo',
          insertForFh: '/lvYifahuomingxi/lvYifahuomingxi/insertForFh',
          remove2: '/lvYifahuomingxi/lvYifahuomingxi/removeFh/',
          listFahuo: '/lvYifahuo/lvYifahuo/',
          add: '/lvYifahuo/lvYifahuo/add',
          edit: '/lvYifahuo/lvYifahuo/edit',
          editDaitijiao: '/lvYifahuo/lvYifahuo/editDaitijiao',
          updateForFh: '/lvYifahuomingxi/lvYifahuomingxi/updateForFh',
          listLinkman: '/goodsShouhuoren/goodsShouhuoren/list',
        },
        tableMaxHeight: window.innerHeight - 320,
      };
    },
    created() {
      // this.intDictsForPrj();
      this.getList2();
      window.addEventListener('resize', this.getTableHeight);
    },
    destroyed() {
      window.removeEventListener('resize', this.getTableHeight);
    },
    methods: {
      reset() {
        this.form = {
          id: null,
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null,
          nos: null,
          name: null,
          fahuoDate: null,
          jiaohuoDate: null,
          linkman: null,
          linktel: null,
          address: null,
          status: "3", //弃审
          jingli: null,
          kehuId: null,
          kehuName: null,
          taxNo: null,
          taxCode: null,
          taxDate: null,
          taxMoney: null,
          taxShengyu: null,
          taxAllmoeny: null,
          allMoney: null,
          shengyu: null,
          yihui: null,
          daohuoDate: null,
          daohuoFile: null,
          fahuoId: null,
        };
        this.resetForm("form");
      },
      /** 提交按钮 */
      submitFormFahuodan() {
        if (this.columns2.length != null && this.columns2.length != '' && this.columns2.length != 'undefined' && this.columns2.length > 0) {
          this.$refs["form"].validate(valid => {
            if (valid) {
              if (this.form.id != null) {
                this.form.columns = this.columns2;
                updateAction(this.url.edit, this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.$emit('ok');
                });
              } else {
                this.form.columns = this.columns2;
                addAction(this.url.add, this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.$emit('ok');
                });
              }
            }
          });
        } else {
          this.$modal.msgError("请选择一条记录");
        }
      },
      submitFormZancun(){
        if (this.columns2.length != null && this.columns2.length != '' && this.columns2.length != 'undefined' && this.columns2.length > 0) {
          this.$refs["form"].validate(valid => {
            if (valid) {
              if (this.form.id != null) {
                this.form.columns = this.columns2;
                updateAction(this.url.editDaitijiao, this.form).then(response => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.$emit('ok');
                });
              } else {
                this.form.columns = this.columns2;
                addAction(this.url.add, this.form).then(response => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.$emit('ok');
                });
              }
            }
          });
        } else {
          this.$modal.msgError("请选择一条记录");
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      selectCustomer(value) {
        let that = this;
        that.$nextTick(() => {
          let arr = that.$refs.myselectCustomer;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.kehuName = arr[i].label;
              that.form.linkman = '';
              that.form.linktel = '';
              that.form.jingli = '';
              that.form.address = '';
              that.queryParamsLinkman.customId = value;
              getAction(this.url.listLinkman, this.queryParamsLinkman).then(response => {
                this.columnsLinkman = response.rows;
              });
            }
          }
        })
      },
      selectShouhuoren(value) {
        let that = this;
        that.$nextTick(() => {
          let arr = that.$refs.myselectShouhuoren;
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].currentValue == value) {
              that.form.linkman = value.shouhuoren;
              that.form.linktel = value.shouhuotel;
              that.form.jingli = value.jingli;
              that.form.address = value.address;
            }
          }
        })
      },
      handleDelete(row) {
        const id = row.id;
        deleteAction(this.url.remove2, id).then(response => {
          this.$modal.msgSuccess("删除成功");
          this.handleQuery();
          this.handleQuery2();
        }).catch(() => {});
      },
      /*updateTotleCost(row) {
        let that = this;
        if (row.shengyu && row.goodsBuyPrice) {
          let totleCost = that.functionNumberMul(row.shengyu, row.goodsBuyPrice);
          that.$set(row, "shengyuCount", totleCost);
        }
      },*/
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.dataList = selection;
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      submitForm() {
        let that = this;
        const ids = this.ids;
        if (ids == null || ids == '' || ids == 'undefined') {
          that.$modal.msgError("请选择一条记录");
          // alert("请选择一条记录");
        } else {
          that.$refs["form"].validate(valid => {
            if (valid) {
              const fahuomingxi = Object.assign({});
              fahuomingxi.columns = that.dataList;
              fahuomingxi.fahuoId = that.queryParams2.fahuoId;
              fahuomingxi.fahuoNo = that.fahuoNo;
              fahuomingxi.status = "3";
              addAction(that.url.insertForFh, fahuomingxi).then(response => {
                that.$modal.msgSuccess("添加成功");
                that.handleQuery();
                that.handleQuery2();
                that.$emit('ok');
              });
            }
          });
        }
      },
      getTableHeight() {
        this.tableHeight = window.innerHeight - 320
      },
      getList2() {
        this.loading2 = true;
        getAction(this.url.list2, this.queryParams2).then(response => {
          this.columns2 = response.rows;
          this.total2 = response.total;
          this.loading2 = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery2() {
        this.queryParams.pageNum = 1;
        this.getList2();
      },
      showModifyMingxi(row) {
        this.queryParams.tongzhiId = row.tongzhiId;
        this.queryParams2.fahuoId = row.id;
        this.fahuoNo = row.nos;
        this.open = true;
        this.getList();
        this.getList2();
        this.reset();
        const id = row.id;
        getById(this.url.listFahuo, id).then(response => {
          this.form = response.data;
        });
      },
      /** 查询销售信息管理列表 */
      getList() {
        this.loading = true;
        getAction(this.url.list, this.queryParams).then(response => {
          this.columns = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
       /** 排序触发事件 */
       handleSortChange(column, prop, order) {
                this.queryParams.orderByColumn = column.prop;
                this.queryParams.isAsc = column.order;
                this.handleQuery();
            },

            totalOutYear(param) {
            const { columns, data } = param;
            const sums = [];

            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                const values = data.map((item) => Number(item[column.property]));
                // 只合计amount1和amount3，想合并哪些列就在这里指定
                if (column.property === "shuliang" ) {

                    sums[index] = values.reduce((prev, curr) => {
                        const value = Number(curr);
                        if (!isNaN(value)) {
                            return accAdd(prev, curr);
                        } else {
                            return prev;
                        }
                    }, 0);
                }
            });
            return sums;
        },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.queryParams.params = {}
        this.resetForm("queryForm");
        this.handleQuery();
      },
    }
  };
</script>
